package com.peter.fragmentcomm.ui.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SeekBar;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.peter.fragmentcomm.R;
import com.peter.fragmentcomm.ui.fragment.data.SharedFragmentData;

public class OneFragment extends Fragment {


    public static Fragment newInstance() {
        return new OneFragment();
    }

    private View parentView;
    private SeekBar seekBar;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        parentView = inflater.inflate(R.layout.fragment_one, container, false);
        seekBar = parentView.findViewById(R.id.seekBar);
        //注意：这里ViewModelProviders.of(getActivity())这里的参数需要是Activity，而不能是Fragment，否则收不到监听
        shareDataViewModel = new ViewModelProvider(getActivity()).get(SharedFragmentData.class);
        return parentView;
    }

    private SharedFragmentData shareDataViewModel;

    @Override
    public void onViewCreated(@NonNull @org.jetbrains.annotations.NotNull View view, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        final MutableLiveData<Integer> liveData = (MutableLiveData<Integer>) shareDataViewModel.getProgress();
        //通过observe方法观察ViewModel中字段数据的变化，并在变化时，得到通知
        liveData.observe(getViewLifecycleOwner(), progress -> seekBar.setProgress(progress));

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                //用户操作SeekBar时，更新ViewModel中的数据
                liveData.setValue(progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }
}
